package com.phenix.mvp.ui.login;

import com.phenix.annotation.apt.Instance;
import com.phenix.mvp.base.mvp.BaseMVPresenter;
import com.phenix.mvp.base.mvp.BaseModel;
import com.phenix.mvp.base.mvp.BaseView;
import com.phenix.mvp.data.Result;
import com.phenix.mvp.data.bean.User;

import io.reactivex.Observable;

/**
 * @author  zhouphenix on 2017-2-21.
 */
@Instance
public class LoginPresenter extends BaseMVPresenter<LoginModel, LoginPresenter.View> {

    interface Model extends BaseModel {
        Observable<Result<User>>login(String name, String pass);
    }

    interface View extends BaseView {
        void loginSuccess();
        void signSuccess();
        void showMsg(String s);
        void showProgress(boolean isShow, String message);
    }


    void login(String name, String pass) {
        addDisposable(mModel.login(name, pass)
                .doOnSubscribe(disposable -> mView.showProgress(true, "正在登录..."))
//                .subscribeOn(AndroidSchedulers.mainThread()) //默认doOnSubscribe 工作与subscribe同一线程，这一句可以指定前者的工作线程
                .subscribe(result -> {
                            if (result.status == 200) {
                                //缓存用户信息
                                mView.loginSuccess();
                            } else {
                                mView.showMsg(result.message);
                            }
                        }, e -> {
                            mView.showMsg("登录失败！" + e.getMessage());
                            mView.showProgress(false, "");
                        },
                        () -> mView.showProgress(false, "")
                ));
    }



    /**
     * 验证email
     * @param email email
     * @return boolean
     */
    protected boolean isEmailValid(String email) {
        return email.contains("@");
    }

    /**
     *  验证密码
     * @param password password
     * @return boolean
     */
    protected boolean isPasswordValid(String password) {
        return password.length() > 4;
    }

}
